<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/5 0005
 * Time: 19:22
 */

class Http
{
    const HOST="0.0.0.0";
    const PORT=9505;
    private $http;
    private $config=[];
    public function __construct($config=[]){
        $this->http=new swoole_http_server(self::HOST,self::PORT);
        $this->config=array_merge($this->config,$config);
        $this->http->set($this->config);
        $this->http->on("WorkerStart",[$this,"onWorkerStart"]);
        $this->http->on("request",[$this,'onRequest']);
        $this->http->on("close",[$this,'onClose']);

        $this->http->on("task",[$this,'onTask']);
        $this->http->on("finish",[$this,'onFinish']);
        $this->http->start();
    }

    /*
     *
     * */
    public function onWorkerStart($server,$worker_id){
        // 定义应用目录
        define('APP_PATH', __DIR__ . '/../application/');
        // 1. 加载基础文件
        require __DIR__ . '/../thinkphp/base.php';
    }

    /*
    监听http消息事件
    */
    public function onRequest($req,$res){
        $_SERVER=[];$_GET=[];$_POST=[];
        if(isset($req->server)){
            foreach($req->server as $key =>$val){
                $_SERVER[strtoupper($key)]=$val;
            }
        }

        if(isset($req->header)){
            foreach($req->header as $key =>$val){
                $_SERVER[strtoupper($key)]=$val;
            }
        }

        if(isset($req->get)){
            foreach($req->get as $key =>$val){
                $_GET[$key]=$val;
            }
        }

        if(isset($req->post)){
            foreach($req->post as $key =>$val){
                $_POST[$key]=$val;
            }
        }

        //打开输出缓冲
        ob_start();
        try{
            // 2. 执行应用
            think\App::run()->send();
        }catch (\Exception $e){
            echo $e->getTraceAsString().PHP_EOL;
            //echo "message:".$e->getMessage().PHP_EOL;
        }
        $data=ob_get_contents();
        ob_end_clean();

        $res->end($data);
        //$http->close();

    }

    /*
    监听http关闭事件
    */
    public function onClose($svr,$fd){
        //echo "{$fd} close";
    }

    /*
    监听task任务事件
    */
    public function onTask($srv,$task_id,$worker_id,$data){
        $task=new \app\common\Task();
        $method=$data['method'];
        return $task->$method($data['data']);
    }

    /*
    监听task任务完成事件
    */
    public function onFinish($srv,$task_id,$data){

    }

}

$http=new Http([
    'document_root' => __DIR__.'/../public/static',
    'enable_static_handler' => true,
    'worker_num'   =>8
]);